package com.st.buy.search.service.impl;

import com.st.buy.manager.mapper.TbItemMapper;
import com.st.buy.pojo.TbItem;
import com.st.buy.search.service.SearchService;
import com.st.buy.util.pojo.BuyResult;
import com.st.buy.util.pojo.SearchItem;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.query.QuerySearchRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张双虎
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private TbItemMapper itemMapper;
    @Autowired
    private RestHighLevelClient client;

    @Value("${indexName}")
    private String indexName;

    public BuyResult importIndex() {
        //查询所有数据  理论上应该分页查询
        List<TbItem> tbItems = itemMapper.selectList(null);
        //直接导入，可以考虑使用批处理
        IndexRequest request = null;
        //直接导入索引库  循环导入
        for(TbItem item : tbItems){
            request  = new IndexRequest(indexName);
            //处理图片
            String image = item.getImage();
            try {
                image = StringUtils.isNoneBlank(image)?(image.split(";")[0]):"";
            } catch (Exception e) {
            }
            //设置数据
            //设置索引文档的id为商品的id
            request.id(item.getId()+"");
            request.source(
                    "itemId",item.getId(),
                    "title",item.getTitle(),
                    "price",item.getPrice(),
                    "sellPoint",item.getSellPoint(),
                    "image",image
            );
            //加入索引库
            try {
                client.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return BuyResult.ok();
    }

    @Override
    public BuyResult importIndex(Long itemId) {
        IndexRequest request  = new IndexRequest(indexName);
        TbItem item = itemMapper.selectById(itemId);
        //处理图片
        String image = item.getImage();
        try {
            image = StringUtils.isNoneBlank(image)?(image.split(";")[0]):"";
        } catch (Exception e) {
        }
        //设置数据
        //设置索引文档的id为商品的id
        request.id(item.getId()+"");
        request.source(
                "itemId",item.getId(),
                "title",item.getTitle(),
                "price",item.getPrice(),
                "sellPoint",item.getSellPoint(),
                "image",image
        );
        //加入索引库
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return BuyResult.ok();
    }

    @Override
    public Map query(String keyword,int page,int rows) {
        List<SearchItem> searchItems = new ArrayList<>();
        long recourdCount = 0;
        //准备查询条件
        SearchRequest request = new SearchRequest(indexName);
        SearchSourceBuilder builder= new SearchSourceBuilder();
        //设置查询条件
        builder.query(QueryBuilders.matchQuery("title",keyword));
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font style='color:red'>");//前缀
        highlightBuilder.postTags("</font>");//后缀
        highlightBuilder.field("title");
        builder.highlighter(highlightBuilder);
        //分页
        builder.from((page-1)*rows);
        builder.size(rows);
        //查询
        request.source(builder);
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //编辑结果集得到要的结果
            //得到hits
            SearchHits hits = response.getHits();
            //得到总条数
            recourdCount = hits.getTotalHits().value;
            //按照iterator的方式迭代
            for(SearchHit hit : hits){
                Map<String, Object> map = hit.getSourceAsMap();
                SearchItem searchItem = new SearchItem();
                searchItem.setItemId(new Long(map.get("itemId").toString()));
                //这里的title是要处理高亮显示的
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField titles = highlightFields.get("title");
                Text[] fragments = titles.fragments();
                String title = fragments!=null && fragments.length>0 ? fragments[0].string():map.get("title").toString();
                searchItem.setTitle(title);
                searchItem.setImage(map.get("image").toString());
                searchItem.setPrice(new Long(map.get("price").toString()));
                searchItem.setSellPoint(map.get("sellPoint").toString());
                searchItems.add(searchItem);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //准备返回值的map
        Map result = new HashMap();
        // 设置数据列表
        result.put("searchItems",searchItems);
        //设置总条数
        result.put("recourdCount",recourdCount);
        return result;
    }
}
